#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"

void prime(int fd){
    char cur[1]={0};
    if(read(fd,cur,1)==0){
        printf("failed to read\n");
        exit(1);
    };
    printf("prime %d\n",cur[0]);
    int first=1;
    char now[1]={0};
    int p[2];
    if(pipe(p)==-1){
        printf("failed to create pipe\n");
        exit(1);
    }
    int pid;
    while(read(fd,now,1)!=0){
        if(first){
            pid=fork();
            first=0;
            if(pid>0){
                close(p[0]);
                write(p[1],now,1);
            }else if(pid==0){
                close(p[1]);
                prime(p[0]);
                close(p[0]);
            }
        } else {
            if(pid){
                if(now[0]%cur[0])write(p[1],now,1);
            }
        }
    }
    close(p[1]);
    wait(0);
    exit(0);
}

int
main(int argc, char *argv[])
{
    if(argc!=1){
        fprintf(2,"usage: primes\n");
        exit(1);
    }
    int p[2];
    if(pipe(p)==-1){
        printf("failed to create pipe\n");
        exit(1);
    }
    int pid=fork();
    if(pid>0){
        close(p[0]);
        char i[1]={2};
        for(;i[0]<=35;i[0]++){
            write(p[1],i,1); 
        }
        close(p[1]);
        wait(0);
    } else if(pid==0){
        close(p[1]);
        prime(p[0]);
        close(p[0]);
        wait(0);
    }
    exit(0);
}
